<?php defined('SYSPATH') or die('No direct script access.');
                          
class User_Controller extends Template_Controller 
{
	public $template = 'layout/user';

	public function __construct()
	{
		parent::__construct();
		
		if( ! cookie::get('userid'))
		{
			url::redirect('/');
			exit;
		}

		$this->template->menu = '';
	}
	
	public function index()
	{
		self::profile();
	}
	
	public function order()
	{
		$model = new Order_Model();
		
		$view = new View('user/order');
		$view->orders = $model->where('customer_id', cookie::get('userid'))
							  ->where('status>=0')->orderby('id', 'desc')->find_all();
		
		$this->template->content = $view->render();
	}
		
	public function cancelorder($order_id)
	{
		$model = new Order_Model($order_id);
		$model->status = -1;
		$model->save();
		url::redirect('user/order');
		exit;
	}
	
	public function profile()
	{
		$model = new Customer_Model(cookie::get('userid'));
		$view = new View('user/profile');
		$view->profile = $model;
		//$view->country = new Country_Model($model->billing_country_id);
		//$view->zone = new Zone_Model($model->billing_zone_id);
		$this->template->content = $view->render();
	}
	
	public function editprofile()
	{
		$model = new Customer_Model(cookie::get('userid'));
		$view = new View('user/profile_form');
		$view->profile = $model;
		//$view->countries = Database::instance()->query('SELECT * FROM countries');
		//$view->zones = Database::instance()->query('SELECT * FROM zones WHERE country_id='.$model->billing_country_id);
		$this->template->content = $view->render();	
	}
	
	public function saveprofile()
	{
		$model = new Customer_Model(cookie::get('userid'));
				
		$model->firstname = $_POST['firstname'];
		$model->lastname = $_POST['lastname'];
		$model->email = $_POST['email'];
		$model->phone = $_POST['phone'];
		$model->fax = $_POST['fax'];
		$model->company = $_POST['company'];
		
		/*$model->billing_country_id = $_POST['billing_country_id'];
		$model->billing_zone_id = $_POST['zone_id'];
		$model->billing_city = $_POST['billing_city'];
		$model->billing_zip_code = $_POST['billing_zip_code'];
		$model->billing_address = $_POST['billing_address'];*/
		
		$model->save();
		
		url::redirect('user/profile', 301);
		exit;
	}
	
	public function changepass()
	{
		$view = new View('user/changepass_form');
		$this->template->content = $view->render();
	}
	
	public function savechangepass()
	{
		$model = new Customer_Model(cookie::get('userid'));
		$model->password = base64_encode($_POST['password']);
		$model->save();
		url::redirect('user/profile', 301);
		exit;
	}
}